import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:my_app_01/model/User.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginPrefs {
  static const String USER_INFO = "USER_INFO"; //用户名
  static const String TOKEN = "TOKEN"; //token

  static late SharedPreferences _prefs; //延迟初始化

  static Future<String> init() async {
    WidgetsFlutterBinding.ensureInitialized();
    _prefs = await SharedPreferences.getInstance();
    return 'ok';
  }

  static void saveUserInfo(UserModel userInfo) {
    _prefs.setString(USER_INFO, jsonEncode(userInfo));
  }

  static UserModel? getUserInfo() {
    String? userStr = _prefs.getString(USER_INFO);
    if (userStr == null) {
      return UserModel();
    } else {
      try {
        return UserModel.fromJson(jsonDecode(userStr));
      } catch (e, s) {
        return UserModel();
      }
    }
  }

  static void saveToken(String token) {
    _prefs.setString(TOKEN, token);
  }

  static String? getToken() {
    return _prefs.getString(TOKEN);
  }

  static void removeUserInfo() {
    _prefs.remove(USER_INFO);
  }

  static void removeToken() {
    _prefs.remove(TOKEN);
  }

  static void clearAuth() {
    _prefs.clear();
  }
}
